﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace WebCommon
{
    public static partial class SharedFunction
    {
        private const int _CONST_LENGTH = 16;

        public static string[] GetSacombankExchangeRate()
        {
            const string url = "http://www.sacombank.com.vn/Pages/default.aspx";

            // Create a request for the URL.         
            WebRequest request = WebRequest.Create(url);

            // Get the response.
            var response = (HttpWebResponse)request.GetResponse();

            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();

            // Open the stream using a StreamReader for easy access.
            if (dataStream != null)
            {
                var reader = new StreamReader(dataStream);

                // Read the content.
                string responseFromServer = reader.ReadToEnd();

                // Remove the DOCTYPE.
                responseFromServer = Regex.Replace(responseFromServer, @"\<\!DOCTYPE.*?\>", string.Empty);

                // Get necessary data
                responseFromServer =
                    responseFromServer.Substring(responseFromServer.LastIndexOf("country1", StringComparison.Ordinal));
                responseFromServer =
                    responseFromServer.Substring(responseFromServer.IndexOf("<table>", StringComparison.Ordinal));
                responseFromServer = responseFromServer.Substring(0,
                                                                  responseFromServer.IndexOf("</table>",
                                                                                             StringComparison.Ordinal));

                var result = new string[_CONST_LENGTH];
                int index = 0;

                while (responseFromServer.IndexOf("current-item", StringComparison.Ordinal) >= 0 &&
                       index < _CONST_LENGTH)
                {
                    responseFromServer = responseFromServer.Substring(responseFromServer.IndexOf("current-item") + 14);
                    string currentRow = responseFromServer.Substring(0, responseFromServer.IndexOf("</tr>"));
                    responseFromServer = responseFromServer.Substring(responseFromServer.IndexOf("</tr>"));

                    string currentValue = currentRow.Substring(currentRow.IndexOf("text") + 6,
                                                               currentRow.IndexOf("</td>") - currentRow.IndexOf("text") - 6).Trim();
                    currentValue = Regex.Replace(currentValue, @"\r", string.Empty);
                    currentValue = Regex.Replace(currentValue, @"\n", string.Empty);
                    currentValue = currentValue.Trim();
                    currentRow = currentRow.Substring(currentRow.IndexOf("</td>") + 5);
                    result[index] = currentValue;
                    index++;

                    currentValue =
                        currentRow.Substring(currentRow.IndexOf("number") + 8,
                                             currentRow.IndexOf("</td>") - currentRow.IndexOf("number") - 8).Trim();
                    currentValue = Regex.Replace(currentValue, @"\r", string.Empty);
                    currentValue = Regex.Replace(currentValue, @"\n", string.Empty);
                    currentValue = currentValue.Trim();
                    currentRow = currentRow.Substring(currentRow.IndexOf("</td>") + 5);
                    result[index] = currentValue;
                    index++;

                    currentValue =
                        currentRow.Substring(currentRow.IndexOf("number") + 8,
                                             currentRow.IndexOf("</td>") - currentRow.IndexOf("number") - 8).Trim();
                    currentValue = Regex.Replace(currentValue, @"\r", string.Empty);
                    currentValue = Regex.Replace(currentValue, @"\n", string.Empty);
                    currentValue = currentValue.Trim();
                    currentRow = currentRow.Substring(currentRow.IndexOf("</td>") + 5);
                    result[index] = currentValue;
                    index++;

                    currentValue =
                        currentRow.Substring(currentRow.IndexOf("number") + 8,
                                             currentRow.IndexOf("</td>") - currentRow.IndexOf("number") - 8).Trim();
                    currentValue = Regex.Replace(currentValue, @"\r", string.Empty);
                    currentValue = Regex.Replace(currentValue, @"\n", string.Empty);
                    currentValue = currentValue.Trim();
                    currentRow = currentRow.Substring(currentRow.IndexOf("</td>") + 5);
                    result[index] = currentValue;
                    index++;
                }

                // Cleanup the streams and the response.
                reader.Close();
                dataStream.Close();
                response.Close();

                // Load the response into an HtmlElement.
                return result;
            }
            return new string[] { };
        }

        public static string GetVCBExchangeRate()
        {
            string url = "http://www.vietcombank.com.vn";

            // Create a request for the URL.         
            WebRequest request = WebRequest.Create(url);

            // Get the response.
            var response = (HttpWebResponse)request.GetResponse();

            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();

            // Open the stream using a StreamReader for easy access.
            var reader = new StreamReader(dataStream);

            // Read the content.
            string responseFromServer = reader.ReadToEnd();

            // Remove the DOCTYPE.
            //responseFromServer = Regex.Replace(responseFromServer, @"\<\!DOCTYPE.*?\>", string.Empty);

            // Get necessary data
            responseFromServer = responseFromServer.Substring(responseFromServer.LastIndexOf("id=\"exchangerate\""));
            responseFromServer = responseFromServer.Substring(responseFromServer.IndexOf("class=\"code\">USD</td><td>"));
            string result = responseFromServer.Substring(43, 9);
            reader.Close();
            dataStream.Close();
            response.Close();

            // Load the response into an HtmlElement.
            return result;
        }

        private static string ExtractViewState(string s)
        {
            const string viewStateNameDelimiter = "__VIEWSTATE";
            const string valueDelimiter = "value=\"";

            int viewStateNamePosition = s.IndexOf(viewStateNameDelimiter);
            int viewStateValuePosition = s.IndexOf(
                valueDelimiter, viewStateNamePosition
                );

            int viewStateStartPosition = viewStateValuePosition +
                                         valueDelimiter.Length;
            int viewStateEndPosition = s.IndexOf("\"", viewStateStartPosition);

            return HttpUtility.UrlEncodeUnicode(
                s.Substring(
                    viewStateStartPosition,
                    viewStateEndPosition - viewStateStartPosition
                    )
                );
        }

        public static string GetVCBHCMExchangeRate()
        {
            //HttpWebRequest httpRequest =
            //(HttpWebRequest)WebRequest.Create("http://www.vietcombank.com.vn/ExchangeRates/Default.aspx");

            //httpRequest.Method = "POST";
            //httpRequest.ContentType = "application/x-www-form-urlencoded";
            //string poststring = String.Format("ctl00$Content$BranchList={0}&ctl00$Content$DateText={1}&ctl00$Content$ViewButton={2}", "7", "14/6/2011","Xem");
            //byte[] bytedata = Encoding.UTF8.GetBytes(poststring);
            //httpRequest.ContentLength = bytedata.Length;

            //Stream requestStream = httpRequest.GetRequestStream();
            //requestStream.Write(bytedata, 0, bytedata.Length);
            //requestStream.Close();


            //HttpWebResponse httpWebResponse =
            //(HttpWebResponse)httpRequest.GetResponse();
            //Stream responseStream = httpWebResponse.GetResponseStream();

            //StringBuilder sb = new StringBuilder();

            //using (StreamReader reader =
            //new StreamReader(responseStream, System.Text.Encoding.UTF8))
            //{
            //    string line;
            //    while ((line = reader.ReadLine()) != null)
            //    {
            //        sb.Append(line);
            //    }
            //}

            //return sb.ToString();
            try
            {
                byte[] response;

                var webClient = new WebClient();
                response = webClient.DownloadData("http://www.vietcombank.com.vn/ExchangeRates/Default.aspx");

                string viewstate = ExtractViewState(
                    Encoding.ASCII.GetString(response)
                    );


                string postData = String.Format(
                    "__VIEWSTATE={0}&__VIEWSTATEENCRYPTED={1}&ctl00$Content$BranchList={2}&ctl00$Content$DateText={3}&ctl00$Content$ViewButton={4}",
                    viewstate, "",
                    "7", DateTime.Now.ToString("d/M/yyyy"), "Xem");


                webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                response = webClient.UploadData(
                    "http://www.vietcombank.com.vn/ExchangeRates/Default.aspx", "POST", Encoding.UTF8.GetBytes(postData)
                    );
                string returnstr = Encoding.UTF8.GetString(response);
                returnstr = returnstr.Substring(returnstr.IndexOf("id=\"ctl00_Content_ExrateView\">"));
                returnstr = returnstr.Substring(returnstr.IndexOf("US DOLLAR</td>"));
                return returnstr.Substring(68, 9);
            }
            catch (Exception)
            {
            }
            return "0";
        }

        //    NameValueCollection values = new NameValueCollection
        //                                     {
        //                                     //    {"ctl00$Content$BranchList", "7"},
        //                                     //    {"ctl00$Content$DateText", DateTime.Now.ToString("dd/M/yyyy")},
        //                                     //    {"ctl00$Content$ViewButton","Xem"}
        //                                     {"field1","a"},
        //                                     {"field2","a"}
        //                                     };


        //    WebClient webclient = new WebClient();

        //    webclient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
        //    byte[] responseArray = webclient.UploadValues(

        //        "http://www.jigar.net/demo/httprequestdemoclient.aspx", "POST",

        //        values);

        //    string response = Encoding.UTF8.GetString(responseArray);
        //    return response.ToString();
        //}
    }
}